from fastapi import FastAPI, Request
from .utilities.exceptions import AppException
from app.models.coop_app import User, Role
from fastapi.middleware.cors import CORSMiddleware
from app.api import user_api, sponsors_api, scholar_api, sponsors_research_api
from fastapi.responses import JSONResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
app = FastAPI()



origins = [
    "http://localhost:5173",
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


app.include_router(user_api.router)
app.include_router(sponsors_api.router)
app.include_router(scholar_api.router)
app.include_router(sponsors_research_api.router) 
@app.exception_handler(AppException)
async def app_exception_handler(request: Request, exc: AppException):
    return exc.to_response()


@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
    return JSONResponse(
        status_code=exc.status_code,
        content={"detail": exc.detail},
        headers={
            "Access-Control-Allow-Origin": "http://localhost:5173",
            "Access-Control-Allow-Credentials": "true",
        }
    )

import logging
import traceback

logger = logging.getLogger(__name__)

@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
    logger.error(f"Unhandled error: {traceback.format_exc()}")

    return JSONResponse(
        status_code=500,
        content={"detail": "Internal Server Error"},
    )